package com.test.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.test.domain.User;
import com.test.repository.UserRepository;

/**
 * 
 * @author Jeff Yang
 * @create 2017年12月4日
 */

@Controller
@RequestMapping("/reimburse")
public class IndexController {

	@Autowired
	private UserRepository userRepository;

	@GetMapping("/index")
	public String loginPage(Model model) {
		model.addAttribute("title", "用户登录");
		return "login";
	}

	@GetMapping("/manage")
	public String manage(Model model) {
		model.addAttribute("title", "管理界面");
		return "manage";
	}

	@PostMapping("/login")
	public ModelAndView login(Model model, User user, HttpSession session) {
		User dbuser = userRepository.findByUsernameAndPassword(user.getUsername(), user.getPassword());
		if (dbuser != null) {
			model.addAttribute("user", dbuser);
			session.setAttribute("user", dbuser);
			return new ModelAndView("/manage", "userModel", model);
		}
		return null;
	}

	@GetMapping("/logout")
	public String loginOut(HttpSession session) {
        //从session中删除user属性，用户退出登录
        session.removeAttribute("user");
        return "/login";
    }
	
}
